package com.uj.speedcalculator;

import java.text.DecimalFormat;

import android.app.Activity;
import android.util.SparseArray;
import android.view.View;
import android.widget.ArrayAdapter;
import android.widget.EditText;
import android.widget.Spinner;
import android.widget.TextView;

/**
 * @author grygula Abstract class to store all useful methods that are not
 *         related directly to current implementation
 */
public abstract class MyActivity extends Activity {

	void setText(int id, double value) {
		if (Double.isNaN(value))
			value = 0;
		EditText f = (EditText) findViewById(id);
		DecimalFormat df = new DecimalFormat("#.##");
		f.setText(df.format(value));
	}

	void setNewList(int id, int list) {
		Spinner s = (Spinner) findViewById(id);
		ArrayAdapter<CharSequence> adapter = ArrayAdapter.createFromResource(
				this, list, android.R.layout.simple_spinner_item);
		adapter.setDropDownViewResource(android.R.layout.simple_spinner_dropdown_item);
		s.setAdapter(adapter);
	}

	String getEditTextString(int id) {
		EditText f = (EditText) findViewById(id);

		return f.getText().toString();
	}

	double getEditTextDouble(int id) {
		String s = getEditTextString(id);
		try {
			double r = Double.parseDouble(s);
			return r;
		} catch (Exception e) {
			return 0.0;
		}
	}

	void setNewTxtForTxtVw(int id, int txt) {
		TextView f = (TextView) findViewById(id);
		f.setText(txt);
	}

	public void clearValues(View v) {
		if (v instanceof EditText) {
			((EditText) v).getText().clear();
		}
	}

	abstract SparseArray<Double> localSetValues(SparseArray<Double> values);

	void setValues(SparseArray<Double> values) {
		values = localSetValues(values);
		int size = values.size();
		for (int i = 0; i < size; i++) {
			int k = values.keyAt(i);
			Double v = values.get(k, 0.0);
			if (v.isNaN())
				v = 0.0;
			setText(k, v);
		}
	}
}
